<?php
class PostsModel extends RelationModel{

	public $_link = array(
			
			'Tag'=>array(
	
					'mapping_type'=>MANY_TO_MANY,
	
					'class_name'   =>'Tags',
	
					'mapping_name'=>'pts',
					
					'foreign_key'=>'post_id',
					
					'relation_foreign_key'=>'tag_id',
					
					'relation_table'=>'post_tag'),
			
			'Cat'=>array(
			
					'mapping_type'=>MANY_TO_MANY,
			
					'class_name'   =>'Cats',
			
					'mapping_name'=>'pcs',
						
					'foreign_key'=>'post_id',
						
					'relation_foreign_key'=>'cat_id',
						
					'relation_table'=>'post_cat'),
	
			'User'=> array(
	
					'mapping_type'=>BELONGS_TO,
		
					'class_name'=>'User',
	
					'foreign_key'=>'user_id', 
	//post_user
					'mapping_name'=>'post_user',
	
					'parent_key'=>'user_id'),
	
			);
	
	

	public function detail($param,$type='single',$status='publish',$relation=true) {
		$info['post_id|post_name']=urlencode(urldecode($param));
		$info['post_type']=$type;
		$info['post_status']=$status;
		
   	 	$post_res = D( 'Posts' )->where ( $info )->relation($relation)->find ();
   	 	return $post_res;
	}
	
	
	public function del($id) {
		$info['post_id']=$id;

		if (D( 'Posts' )->where ( $info )->relation(true)->delete () )
			return true;
		else
			return false;
	}
	
	
	
	public function post_list($order= 'post_id desc',$limit=20,$type='single',$relation=false) {
		
		$info['post_type']=$type;
		
		$post_list = D( 'Posts' )->where ( $info )->order (' post_top desc ,' .$order)->limit ( $limit )->relation($relation)->select ();
		
		Log::write( D( 'Posts' )->getLastSql());
		
		return $post_list;
	}
	
	public function count_all($type='single') {
	
		$info['post_type']=$type;
	
		$count = D( 'Posts' )->where ( $info )->count ();
	
		return $count;
	}
	

	public function post_list_page($Page,$type='single',$order= 'post_id desc',$status='publish',$info) {
	
		$info ['post_type'] = $type;
		$info ['post_status'] = $status;
		
		$info['post_type']=$type;
	
		$post_list = D( 'Posts' )->where ( $info )->relation ( true )->order (' post_top desc ,' .$order )->limit ( $Page->firstRow . ',' . $Page->listRows )->select ();
	
		return $post_list;
	}
	
}